package com.lzw.spring_cache_redis.service.impl;

import com.lzw.spring_cache_redis.dao.UserDao;
import com.lzw.spring_cache_redis.pojo.User;
import com.lzw.spring_cache_redis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @program: spring_cache_redis
 * @description: 用户实现类使用Spring缓存注解
 * @author: lizhiwei
 * @create: 2019-06-13 23:41
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao = null;

    //获取id,去参数id缓存用户
    @Override
    @Transactional
    @CachePut(value = "redisCache",key = "'redis_user_'+#id")
    public User getUser(Long id) {
        return userDao.getUser(id);
    }

    //插入用户，最后MyBatis会回填id,取结果id缓存用户
    @Override
    @Transactional
    @CachePut(value = "redisCache",key = "'redis_user_'+#result.id")
    public User inserUser(User user) {
        userDao.inserUser(user);
        return user;
    }

    //更新数据后，更新缓存，如果condition配置项使结果返回null，不缓存
    @Override
    @Transactional
    @Cacheable(value = "redisCache",key = "'redis_user_'+#id")
    public User updateUserName(Long id,String userName) {
        User user = this.getUser(id);
        if (user == null){
            return null;
        }
        user.setUserName(userName);
        userDao.updateUser(user);
        return user;
    }

    //命中率低，所以不采用缓存机制
    @Override
    public List<User> findUsers(String userName, String note) {
        return userDao.findUsers(userName,note);
    }

    //移除缓存
    @Override
    @Transactional
    @CacheEvict(value = "redisCache" ,key = "'redis_user_'+#id",beforeInvocation = false)
    public int deleteUser(Long id) {
        return userDao.deleteUser(id);
    }
}
